package manager

import (
	"bytes"
	"errors"
	"fmt"
	"gitcode.com/G-YT/ANN/server/global"
	"gitcode.com/G-YT/ANN/server/model/manager"
	managerReq "gitcode.com/G-YT/ANN/server/model/manager/request"
	managerRes "gitcode.com/G-YT/ANN/server/model/manager/response"
	"gitcode.com/G-YT/ANN/server/model/system"
	systemRes "gitcode.com/G-YT/ANN/server/model/system/response"
	"gitcode.com/G-YT/ANN/server/model/user"
	"gitcode.com/G-YT/ANN/server/utils"
	"github.com/xuri/excelize/v2"
	"gorm.io/gorm"
	"strconv"
	"strings"
	"time"
)

type FdHealthManagerService struct {
}

// CreateFdHealthManager 创建fdHealthManager表记录
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) CreateFdHealthManager(fdHealthManager *manager.FdHealthManager) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		var info manager.FdHealthManager
		fErr := tx.First(&info, "phone = ?", fdHealthManager.Phone).Error
		var healthManagerRegister manager.FdHealthManagerRegister
		fdHealthManager.CreatedAt = time.Now()
		fdHealthManager.IsRegister = utils.Pointer(false)
		fdHealthManager.IsAudit = utils.Pointer(false)
		fdHealthManager.DirectNum = utils.Pointer(0)
		fdHealthManager.IndirectNum = utils.Pointer(0)
		fdHealthManager.ServedNum = utils.Pointer(0)
		fdHealthManager.Password = utils.BcryptHash(fdHealthManager.Password)
		if fErr == nil { // 如果该手机号已注册
			tx.Where("hm_id = ?", info.HmId).First(&healthManagerRegister)
			if info.Phone != "" && *healthManagerRegister.RegisterStatus == 2 { // 如果该账号注册被驳回了重新申请
				if err = tx.Where("hm_id = ? ", info.HmId).First(&info).
					Updates(map[string]interface{}{
						"store_id":  fdHealthManager.StoreId,
						"password":  fdHealthManager.Password,
						"name":      fdHealthManager.Name,
						"studentID": fdHealthManager.StudentID,
					}).Error; err != nil {
					return err
				}
				if err = tx.Where("hm_id = ?", healthManagerRegister.HmId).First(&healthManagerRegister).
					Updates(map[string]interface{}{
						"register_status": 0,
						"register_info":   "",
					}).Error; err != nil {
					return err
				}
			} else { // 否则让健管师联系服务站
				return errors.New("該手機號碼已註冊，請聯繫服務站進行審核！")
			}
		} else { // 如果该手机号未注册
			err = tx.Create(fdHealthManager).Error
			if err != nil {
				return err
			}
			fdHealthManagerRegister := manager.FdHealthManagerRegister{
				HmId:           fdHealthManager.HmId,
				RegisterStatus: utils.Pointer(0),
				RegisterInfo:   "",
			}
			err = tx.Create(&fdHealthManagerRegister).Error
			targetPlan := manager.TargetPlan{
				HmId:      fdHealthManager.HmId,
				CreatedAt: time.Time{},
			}
			err = tx.Create(&targetPlan).Error
		}
		return err
	})
}

func (fdHealthManagerService *FdHealthManagerService) Login(fdHealthManager *manager.FdHealthManager) (*manager.FdHealthManager, error) {
	var user manager.FdHealthManager
	err := global.GVA_DB.First(&user, "phone = ?", fdHealthManager.Phone).Error
	if err != nil {
		return nil, errors.New("該帳號未註冊")
	}
	var healthManagerRegister manager.FdHealthManagerRegister
	rErr := global.GVA_DB.Where("hm_id = ?", user.HmId).First(&healthManagerRegister).Error
	if rErr != nil {
		return nil, rErr
	}
	if *healthManagerRegister.RegisterStatus == 2 {
		return nil, errors.New("該帳號註冊申請已被駁回，請重新註冊")
	}
	if err != nil {
		return nil, errors.New("該手機號碼未註冊")
	}
	if user.IsRegister != nil && !*user.IsRegister {
		return nil, errors.New("該手機號碼註冊審核中")
	}
	if !utils.BcryptCheck(fdHealthManager.Password, user.Password) {
		return nil, errors.New("用戶名稱或密碼錯誤")
	}
	return &user, nil
}

// DeleteFdHealthManager 删除fdHealthManager表记录
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) DeleteFdHealthManager(fdHealthManager manager.FdHealthManager) (err error) {
	err = global.GVA_DB.Delete(&fdHealthManager, "hm_id = ?", fdHealthManager.HmId).Error
	return err
}

// DeleteFdHealthManagerByIds 批量删除fdHealthManager表记录
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) DeleteFdHealthManagerByIds(ids managerReq.IdsHReq) (err error) {
	err = global.GVA_DB.Delete(&[]manager.FdHealthManager{}, "hm_id in ?", ids.Ids).Error
	return err
}

// UpdateFdHealthManager 更新fdHealthManager表记录
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) UpdateFdHealthManager(fdHealthManager manager.FdHealthManager) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		var serviceStation system.SysUser
		if serviceStationErr := tx.Model(&system.SysUser{}).First(&serviceStation, "id = ?", fdHealthManager.StoreId).Error; serviceStationErr != nil {
			return serviceStationErr
		}
		if fdHealthManager.OpenNum != 0 && serviceStation.OpenNum < fdHealthManager.OpenNum {
			return errors.New("已超出服務站開通會員授權次數，請聯繫超級管理員！")
		} else {
			// 更新服务站开通会员授权次数
			serviceStation.OpenNum = serviceStation.OpenNum - fdHealthManager.OpenNum
			if updateSsErr := tx.Model(&system.SysUser{}).Where("id = ?", fdHealthManager.StoreId).Update("open_num", serviceStation.OpenNum).Error; updateSsErr != nil {
				return updateSsErr
			}
			// 更新健管师表
			fdHealthManager.UpdatedAt = time.Now()
			if updateHmErr := tx.Save(&fdHealthManager).Error; err != nil {
				return updateHmErr
			}
		}
		return nil
	})
}

// OpenVip 开通会员
func (fdHealthManagerService *FdHealthManagerService) OpenVip(HmID, authority uint, uid, vipType string) (err error) {
	if authority != 888 { // 如果不是超级管理员
		var healthManager manager.FdHealthManager
		if healthManagerErr := global.GVA_DB.Model(&manager.FdHealthManager{}).First(&healthManager, "hm_id = ?", HmID).Error; healthManagerErr != nil {
			return healthManagerErr
		}
		if healthManager.OpenNum == 0 {
			return errors.New("開通會員次數已不足，請聯繫服務站進行授權！")
		}
	}
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		vType, _ := strconv.Atoi(vipType)
		var dataMap = make(map[string]int)
		dataMap["0"] = 0
		dataMap["1"] = 30
		dataMap["2"] = 90
		dataMap["3"] = 180
		dataMap["4"] = 365
		var expiredAt time.Time

		if day, ok := dataMap[vipType]; ok {
			expiredAt = time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.Now().Location()).AddDate(0, 0, day)
		}

		var applyForAt time.Time // 更新后申请时间
		applyForAt = time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.Now().Location())

		// 获取当前用户开通记录
		recordErr := tx.Order("id DESC").First(&user.Vip{}, "uid = ?", uid)
		if errors.Is(recordErr.Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
			uintUid, _ := strconv.ParseUint(uid, 10, 64)
			if createErr := tx.Create(&user.Vip{
				Uid:            uint(uintUid),
				CreatedAt:      applyForAt,
				UpdatedAt:      time.Now(),
				ExpiredAt:      &expiredAt,
				ApplyForAt:     applyForAt,
				VipType:        uint(vType),
				Status:         2,
				OpID:           HmID,
				OpenPersonType: 2,
			}).Error; createErr != nil {
				return createErr
			}
		} else {
			if upErr := tx.Order("id DESC").First(&user.Vip{}, "uid = ?", uid).Updates(map[string]interface{}{
				"expired_at":       expiredAt,
				"apply_for_at":     applyForAt,
				"vip_type":         uint(vType),
				"status":           2,
				"op_id":            HmID,
				"open_person_type": 2,
			}).Error; upErr != nil {
				return upErr
			}
		}
		// 扣除健管师开通授权数
		if updateErr := tx.First(&manager.FdHealthManager{}, "hm_id = ?", HmID).Update("open_num", gorm.Expr("open_num - ?", 1)).Error; updateErr != nil {
			return updateErr
		}
		// 修改用户类型
		if updateErr := tx.Model(&user.User{}).Where("id = ?", uid).Update("types", 2).Error; updateErr != nil {
			return updateErr
		}
		return nil
	})
}

// ChangePassword 修改用户密码
func (fdHealthManagerService *FdHealthManagerService) ChangePassword(id uint, newPassword string) (err error) {
	Password := utils.BcryptHash(newPassword)
	err = global.GVA_DB.Model(&manager.FdHealthManager{}).Where("hm_id = ?", id).Update("password", Password).Error
	return
}

// GetFdHealthManager 根据id获取fdHealthManager表记录
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetFdHealthManager(id string) (fdHealthManager manager.FdHealthManager, err error) {
	err = global.GVA_DB.Where("hm_id = ?", id).First(&fdHealthManager).Error
	return
}

// FindHealthManagerByWhere 根据条件获取健管师信息
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) FindHealthManagerByWhere(info managerReq.FdHealthManagerSearch) (fdHealthManager manager.FdHealthManager, err error) {
	db := global.GVA_DB.Model(&manager.FdHealthManager{}).Preload("HealthManageCenter", func(db *gorm.DB) *gorm.DB {
		return db.Preload("CreatorInfo")
	})
	if info.Phone != "" {
		db = db.Where("phone = ?", info.Phone)
	}
	err = db.First(&fdHealthManager).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return fdHealthManager, errors.New("不存在該帳號的健管師")
	}
	return
}

// GetHealthManagersByHmIDs 根据ID集合获取健管师列表【超管】
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetHealthManagersByHmIDs(info managerReq.HealthManagerIDs) (list []managerRes.ManagerNameList, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&manager.FdHealthManager{})
	if info.UIDs != "" {
		IDsStr := strings.Trim(info.UIDs, "[]")
		IDsArr := strings.Split(IDsStr, ",")
		db = db.Where("fd_health_manager.hm_id IN (?)", IDsArr)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	err = db.Select("fd_health_manager.hm_id, fd_health_manager.name, fd_health_manager.sex, fd_health_manager.phone," +
		"b.name AS serviceStation,c.name AS serviceCenter").
		Joins("LEFT JOIN sys_users AS b ON fd_health_manager.store_id = b.id").
		Joins("LEFT JOIN sys_users AS c ON b.creator = c.id").
		Order("fd_health_manager.hm_id ASC").
		Scan(&list).Error
	return
}

// GetSsHealthManagerList 获取健管师列表【服务站】
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetSsHealthManagerList(info managerReq.FdHealthManagerSearch) (list []manager.FdHealthManager, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&manager.FdHealthManager{}).Omit("password").Where("store_id = ?", info.StoreId)
	var fdHealthManagers []manager.FdHealthManager
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Phone != "" {
		db = db.Where("phone = ?", info.Phone)
	}
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	err = db.Find(&fdHealthManagers).Error
	return fdHealthManagers, total, err
}

// GetScHealthManagerList 获取健管师列表【服务中心】
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetScHealthManagerList(info managerReq.FdHealthManagerSearch, ScID uint) (list []manager.FdHealthManager, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	var serviceStations []system.SysUser
	err = global.GVA_DB.Model(&system.SysUser{}).Where("creator = ?", ScID).Find(&serviceStations).Error
	var ids []uint
	for _, v := range serviceStations {
		ids = append(ids, v.ID)
	}
	db := global.GVA_DB.Model(&manager.FdHealthManager{}).Omit("password").Where("store_id IN (?)", ids)
	var fdHealthManagers []manager.FdHealthManager
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Phone != "" {
		db = db.Where("phone = ?", info.Phone)
	}
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	err = db.Find(&fdHealthManagers).Error
	return fdHealthManagers, total, err
}

// GetAllHealthManagerInfoList 分页获取所有健管师记录
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetAllHealthManagerInfoList(info managerReq.FdHealthManagerSearch) (list []manager.FdHealthManager, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&manager.FdHealthManager{}).Omit("password")
	var fdHealthManagers []manager.FdHealthManager
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.IsRegister != nil {
		db = db.Where("is_register = ?", info.IsRegister)
	}
	if info.IsAudit != nil {
		db = db.Where("is_audit = ?", info.IsAudit)
	}
	if info.StoreId != 0 {
		db = db.Where("store_id = ?", info.StoreId)
	}
	if info.Phone != "" {
		db = db.Where("phone = ?", info.Phone)
	}
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	err = db.Find(&fdHealthManagers).Error
	return fdHealthManagers, total, err
}

// GetHealthManagerRank 获取健管师排名【超管】
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetHealthManagerRank(info managerReq.ManagerRank) (list []managerRes.ManagerRank, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 当日时间戳
	// 判断今日是否已创建对该用户的消息提醒
	startTime := time.Now().Format("2006-01-02")
	endTime := time.Now().AddDate(0, 0, 1).Format("2006-01-02")
	// 创建db
	db := global.GVA_DB.Model(&manager.FdHealthManager{}).Omit("password").
		Select("fd_health_manager.hm_id AS id, fd_health_manager.name, fd_health_manager.phone, fd_health_manager.grade, store_id,fd_health_manager.sex, (fd_health_manager.direct_num + fd_health_manager.indirect_num) AS registerNum," +
			"(SELECT COUNT(*) FROM fd_user AS u WHERE u.steward_id = fd_health_manager.hm_id AND u.types = 2) AS payNum," +
			"(SELECT COUNT(*)  FROM fd_message_remind AS b WHERE b.hm_id = fd_health_manager.hm_id AND b.created_at BETWEEN " + startTime + " AND " + endTime + " AND b.score = 5 AND b.status = 1 ) AS served_num," +
			"fd_health_manager.score,c.name AS serviceStation,d.name AS serviceCentre")
	var ServiceStations []system.SysUser
	var ServiceStation system.SysUser
	var ServiceCentres system.SysUser
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.ServiceCentre != 0 { // 只有服务中心
		ServiceCentreInfo := global.GVA_DB.Where("authority_id = 333 AND id = ?", info.ServiceCentre).First(&ServiceCentres).Error
		if ServiceCentreInfo != nil {
			return nil, 0, ServiceCentreInfo
		}
		result := global.GVA_DB.Where("authority_id = 444 AND creator = ?", ServiceCentres.ID).Find(&ServiceStations).Error
		if result != nil {
			return nil, 0, result
		}
		var ids []uint
		for _, v := range ServiceStations {
			ids = append(ids, v.ID)
		}
		db = db.Where("store_id IN (?)", ids)
	}
	if info.ServiceStation != 0 && info.ServiceCentre != 0 { // 服务站和服务中心
		ServiceStationInfo := global.GVA_DB.Where("authority_id = 444 AND id = ?", info.ServiceStation).First(&ServiceStation).Error
		if ServiceStationInfo != nil {
			return nil, 0, ServiceStationInfo
		}
		db = db.Where("store_id = (?)", ServiceStation.ID)
	}
	if info.Grade != 0 {
		db = db.Where("grade = ?", info.Grade)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	db.Joins("LEFT JOIN sys_users AS c ON fd_health_manager.store_id = c.id").
		Joins("LEFT JOIN sys_users AS d ON c.creator = d.id").
		//Joins("LEFT JOIN fd_message_remind AS b on b.hm_id = fd_health_manager.hm_id AND b.hm_id = fd_health_manager.hm_id AND b.created_at BETWEEN ? AND ? AND b.score = 5 AND b.status = 1", startTime, endTime).
		Group("`fd_health_manager`.`hm_id`").Order("payNum DESC").Scan(&list)
	return list, total, err
}

// GetScHealthManagerRank 获取健管师排名【服务中心】
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetScHealthManagerRank(info managerReq.ManagerRank) (list []managerRes.ManagerRank, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 当日时间戳
	// 判断今日是否已创建对该用户的消息提醒
	startTime := time.Now().Format("2006-01-02")
	endTime := time.Now().AddDate(0, 0, 1).Format("2006-01-02")
	// 创建db
	db := global.GVA_DB.Model(&manager.FdHealthManager{}).Omit("password").
		Select("fd_health_manager.hm_id AS id, fd_health_manager.name, fd_health_manager.phone, fd_health_manager.grade, store_id,fd_health_manager.sex, (fd_health_manager.direct_num + fd_health_manager.indirect_num) AS registerNum," +
			"(SELECT COUNT(*) FROM fd_user AS u WHERE u.steward_id = fd_health_manager.hm_id AND u.types = 2) AS payNum," +
			"(SELECT COUNT(*) FROM fd_message_remind AS b WHERE b.hm_id = fd_health_manager.hm_id AND b.created_at BETWEEN " + startTime + " AND " + endTime + " AND b.score = 5 AND b.status = 1 ) AS served_num," +
			"fd_health_manager.score,c.name AS serviceStation,d.name AS serviceCentre")
	var ServiceStations []system.SysUser
	var ServiceStation system.SysUser
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.ServiceStation == 0 {
		// 获取服务中心下属服务站
		result := global.GVA_DB.Where("authority_id = 444 AND creator = ?", info.ServiceCentre).Find(&ServiceStations).Error
		if result != nil {
			return nil, 0, result
		}
		var ids []uint
		for _, v := range ServiceStations {
			ids = append(ids, v.ID)
		}
		db = db.Where("store_id IN (?)", ids)
	} else {
		ServiceStationInfo := global.GVA_DB.Where("authority_id = 444 AND id = ?", info.ServiceStation).First(&ServiceStation).Error
		if ServiceStationInfo != nil {
			return nil, 0, ServiceStationInfo
		}
		db = db.Where("store_id = (?)", ServiceStation.ID)
	}
	if info.Grade != 0 {
		db = db.Where("grade = ?", info.Grade)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}
	db.Joins("LEFT JOIN sys_users AS c ON fd_health_manager.store_id = c.id").
		Joins("LEFT JOIN sys_users AS d ON c.creator = d.id").
		Group("`fd_health_manager`.`hm_id`").Order("payNum DESC").Scan(&list)
	return list, total, err
}

// ExportExcel 导出健管师Excel【超管】
// Author [g-qs](https://github.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) ExportExcel(info managerReq.FdHealthManagerSearch) (file *bytes.Buffer, name string, err error) {
	// 创建db
	db := global.GVA_DB.Model(&manager.FdHealthManager{}).Omit("password").Where("store_id = ?", info.StoreId)
	var fdHealthManagers []manager.FdHealthManager
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Phone != "" {
		db = db.Where("phone = ?", info.Phone)
	}
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}

	err = db.Find(&fdHealthManagers).Error

	f := excelize.NewFile()
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()
	// Create a new sheet.
	index, err := f.NewSheet("Sheet1")
	if err != nil {
		fmt.Println(err)
		return
	}

	tableTitle := []string{"姓名", "電話", "身份證號", "學號", "級別", "評分", "邀請人數", "服務會員數", "認證時間"}

	var userGradeMap = make(map[uint]string)
	userGradeMap[1] = "初級"
	userGradeMap[2] = "中級"
	userGradeMap[3] = "高級"

	var rows [][]string
	rows = append(rows, tableTitle)
	for _, healthManager := range fdHealthManagers {
		row := []string{
			healthManager.Name,
			healthManager.Phone,
			fmt.Sprintf("%s", healthManager.IDCard),
			fmt.Sprintf("%s", healthManager.StudentID),
			userGradeMap[healthManager.Grade],
			strconv.Itoa(int(healthManager.Score)),
			fmt.Sprintf("%d", *healthManager.DirectNum+*healthManager.IndirectNum),
			fmt.Sprintf("%d", *healthManager.ServedNum),
			healthManager.CreatedAt.Format("2006-01-02 15:04:05"),
		}
		rows = append(rows, row)
	}
	for i, row := range rows {
		for j, colCell := range row {
			err := f.SetCellValue("Sheet1", fmt.Sprintf("%c%d", 'A'+j, i+1), colCell)
			if err != nil {
				return nil, "", err
			}
		}
	}
	f.SetActiveSheet(index)
	file, err = f.WriteToBuffer()
	if err != nil {
		return nil, "", err
	}

	return file, "健管師列表", err
}

// ExportScExcel 导出健管师Excel【服务中心】
// Author [g-qs](https://github.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) ExportScExcel(info managerReq.FdHealthManagerSearch, ScID uint) (file *bytes.Buffer, name string, err error) {
	// 创建db
	var serviceStations []system.SysUser
	var ServiceCentres system.SysUser
	if ServiceCentreInfo := global.GVA_DB.Where("authority_id = 333 AND id = ?", ScID).First(&ServiceCentres).Error; ServiceCentreInfo != nil {
		return
	}
	err = global.GVA_DB.Model(&system.SysUser{}).Where("creator = ?", ScID).Find(&serviceStations).Error
	var ids []uint
	for _, v := range serviceStations {
		ids = append(ids, v.ID)
	}
	db := global.GVA_DB.Model(&manager.FdHealthManager{}).Omit("password").Where("store_id IN (?)", ids)
	var fdHealthManagers []manager.FdHealthManager
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.Phone != "" {
		db = db.Where("phone = ?", info.Phone)
	}
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}

	err = db.Find(&fdHealthManagers).Error

	f := excelize.NewFile()
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()
	// Create a new sheet.
	index, err := f.NewSheet("Sheet1")
	if err != nil {
		return
	}

	tableTitle := []string{"姓名", "電話", "身份證號", "學號", "級別", "評分", "邀請人數", "服務會員數", "認證時間"}

	var userGradeMap = make(map[uint]string)
	userGradeMap[1] = "初級"
	userGradeMap[2] = "中級"
	userGradeMap[3] = "高級"

	var rows [][]string
	rows = append(rows, tableTitle)
	for _, healthManager := range fdHealthManagers {
		row := []string{
			healthManager.Name,
			healthManager.Phone,
			fmt.Sprintf("%s", healthManager.IDCard),
			fmt.Sprintf("%s", healthManager.StudentID),
			userGradeMap[healthManager.Grade],
			strconv.Itoa(int(healthManager.Score)),
			fmt.Sprintf("%d", *healthManager.DirectNum+*healthManager.IndirectNum),
			fmt.Sprintf("%d", *healthManager.ServedNum),
			healthManager.CreatedAt.Format("2006-01-02 15:04:05"),
		}
		rows = append(rows, row)
	}
	for i, row := range rows {
		for j, colCell := range row {
			err := f.SetCellValue("Sheet1", fmt.Sprintf("%c%d", 'A'+j, i+1), colCell)
			if err != nil {
				return nil, "", err
			}
		}
	}
	f.SetActiveSheet(index)
	file, err = f.WriteToBuffer()
	if err != nil {
		return nil, "", err
	}

	return file, ServiceCentres.Name + "健管師列表", err
}

// GetStewardListByPage 根据分页获取健管师列表
// Author [g-qs](https://github.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetStewardListByPage(info managerReq.FdHealthManagerSearch) (list []managerRes.ManagerList, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	//db := global.GVA_DB.Model(&structure.Steward{})
	db := global.GVA_DB.Model(&manager.FdHealthManager{})
	//var stewards []structure.Steward
	var managers []manager.FdHealthManager
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.Name != "" {
		db = db.Where("name LIKE ?", "%"+info.Name+"%")
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	//err = db.Limit(limit).Offset(offset).Preload("ServiceCenter").Find(&stewards).Error
	err = db.Limit(limit).Offset(offset).Preload("HealthManageCenter").Find(&managers).Error
	for i := range managers {
		var healthCenter system.SysUser
		global.GVA_DB.Where("id = ?", managers[i].StoreId).First(&healthCenter)
		// 获取星月日数
		stars, moons, suns := getSmsNum(managers[i].Score)
		var Grade string
		if managers[i].Grade == 1 {
			Grade = "初級"
		} else if managers[i].Grade == 2 {
			Grade = "中級"
		} else if managers[i].Grade == 3 {
			Grade = "高級"
		}
		list = append(list, managerRes.ManagerList{
			ID:                managers[i].HmId,
			Name:              managers[i].Name,
			Avatar:            managers[i].HeaderImg,
			Level:             Grade,
			StudentID:         managers[i].StudentID,
			Score:             managers[i].Score,
			Stars:             stars,
			Moons:             moons,
			Suns:              suns,
			ServiceCenterAddr: healthCenter.Name,
		})
	}
	return list, total, err
}

// GetServiceCenterList 获取服务中心列表
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetServiceCenterList() (list []systemRes.HealthManageCenter, err error) {
	err = global.GVA_DB.Model(&system.SysUser{}).Select("id,nick_name,name").Where("authority_id = ? AND enable = ?", 333, 1).Find(&list).Error
	return list, err
}

// GetHealthManageCenterList 获取健管中心列表
// Author [g-qs](https://gitee.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetHealthManageCenterList(ID string) (list []systemRes.HealthManageCenter, err error) {
	db := global.GVA_DB.Model(&system.SysUser{}).Select("id,nick_name,name,creator").Where("authority_id = 444 AND enable = 1")
	if ID != "" {
		db = db.Where("creator = ?", ID)
	}
	err = db.Find(&list).Error
	return
}

// GetHealthManagerInfo 根据ID获取健管师个人信息
// Author [g-qs](https://github.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetHealthManagerInfo(id uint) (fdHealthManager manager.FdHealthManager, err error) {
	err = global.GVA_DB.Where("hm_id = ?", id).Preload("HealthManageCenter", func(db *gorm.DB) *gorm.DB {
		return db.Preload("CreatorInfo")
	}).First(&fdHealthManager).Error
	return
}

// UpdateFdHealthManagerInfo 根据ID修改健管师信息
// Author [g-qs](https://github.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) UpdateFdHealthManagerInfo(fdHealthManager manager.FdHealthManager) (err error) {
	fdHealthManager.UpdatedAt = time.Now()
	if updateHmErr := global.GVA_DB.Where("hm_id = ?", fdHealthManager.HmId).Updates(&fdHealthManager).Error; updateHmErr != nil {
		return updateHmErr
	}
	return nil
}

// ApplyAttestation 申请认证
// Author [g-qs](https://github.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) ApplyAttestation(hmID uint) (err error) {
	var attestation manager.FdHealthManagerAudit
	err = global.GVA_DB.Where("hm_id = ?", hmID).Order("id Desc").First(&attestation).Error
	if attestation.ID != 0 && *attestation.AuditStatus != 2 {
		return errors.New("請勿重複提交申請")
	}
	result := manager.FdHealthManagerAudit{
		HmId:        hmID,
		AuditStatus: utils.Pointer(0),
	}
	err = global.GVA_DB.Create(&result).Error
	return
}

// GetAttestationFailReason 认证失败原因
// Author [g-qs](https://github.com/g-qs)
func (fdHealthManagerService *FdHealthManagerService) GetAttestationFailReason(hmId uint) (Info string, err error) {
	var attestation manager.FdHealthManagerAudit
	err = global.GVA_DB.Where("hm_id = ? AND audit_status = 2", hmId).Order("id Desc").First(&attestation).Error
	return attestation.AuditInfo, err
}

// 获取星星、月亮、太阳的数量
func getSmsNum(num uint) (stars, moons, suns uint) {
	suns = num / 5000
	// 剩余数量
	remaining := num % 5000
	// 计算月亮数量
	moons = remaining / 1000
	// 剩余数量
	remaining %= 1000
	// 计算星星数量
	stars = remaining / 100
	return stars, moons, suns
}
